package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.UserDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {

        private StringRedisTemplate stringRedisTemplate;

        public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
            this.stringRedisTemplate = stringRedisTemplate;
        }

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            String requestURI = request.getRequestURI();
            System.out.println(requestURI);

            String token = request.getHeader("Authorization");

            if (StringUtils.isEmpty(token)) {

                return true;
            }

            Map<Object, Object> objectObjectMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);

            if (objectObjectMap.isEmpty()) {
                return true;
            }

            UserDTO userDTO = BeanUtil.fillBeanWithMap(objectObjectMap, new UserDTO(),false);

            UserHolder.saveUser(userDTO);

            stringRedisTemplate.expire(LOGIN_USER_KEY + token,LOGIN_USER_TTL, TimeUnit.MINUTES);

            return true;
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            UserHolder.removeUser();
        }
    }
